package org.groupg.project;

import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroovyTemplateWithScriptExample {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 创建模板字符串，包含 Groovy 脚本
        String templateText = """
            Hello, ${user.name}!
            You have ${messages.size()} new messages.
            %{-- 使用 Groovy 脚本计算未读消息数 --}%
            def unreadMessages = messages.count { it.startsWith("Unread") }
            Unread messages: ${unreadMessages}
            %{-- 条件判断 --}%
            %{ if (unreadMessages > 0) { }%
                You have some unread messages.
            %{ } else { }%
                All messages are read.
            %{ } }%
            Messages:
            %{-- 遍历消息列表 --}%
            ${messages.each { msg -> println(" - " + msg) }}
        """;

        // 创建模板引擎
        SimpleTemplateEngine engine = new SimpleTemplateEngine();

        // 创建模板
        Template template = engine.createTemplate(templateText);

        // 创建绑定变量
        Map<String, Object> binding = new HashMap<>();

        // 创建自定义对象
        User user = new User("Alice");
        binding.put("user", user);

        // 创建消息列表
        List<String> messages = List.of("Unread Message 1", "Read Message 2", "Unread Message 3");
        binding.put("messages", messages);

        // 执行模板并获取结果
        StringWriter writer = new StringWriter();
        template.make(binding).writeTo(writer);

        // 打印结果
        System.out.println(writer.toString());
    }

    // 自定义 User 类
    static class User {
        private String name;

        public User(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }
}
